// uses mock4as version 1.0
package com.mocksamples.subscriber
{
    import flexunit.framework.TestCase;
    import flexunit.framework.TestSuite;
	import org.mock4as.Mock;

    public class PublisherTest extends TestCase
	{
		private const MSG1:String = "MESSAGE1";
		private const MSG2:String = "MESSAGE2";

		public function PublisherTest(methodName : String){
            super(methodName);
        }
            		
		public function subscriberReceivesMessage():void{
			// create the mock
			var subscriber:MockSubscriber = new MockSubscriber();
			// set expectations
			subscriber.expects("receive").times(1).withArg(MSG1).noReturn();
			subscriber.expects("receive").times(1).withArg(MSG2).noReturn();
			// inject the mock			
			var myPublisher:Publisher = new Publisher();
			myPublisher.add(subscriber);
			// execute 
			myPublisher.publish(MSG1);
			myPublisher.publish(MSG2);
			// verify mock behavior
			subscriber.verify();
			// show mock expectation error message if any
			assertNull(subscriber.errorMessage());
		}  			
		public function onlyTheLasSubscriberReceivesTheMessage():void{
			// create the mock
			var firstSubscriber:MockSubscriber = new MockSubscriber();
			var lastSubscriber:MockSubscriber = new MockSubscriber();
			// set expectations
			lastSubscriber.expects("receive").times(1).withArg(MSG1).noReturn();
			// inject the mock			
			var myPublisher:Publisher = new Publisher();
			myPublisher.add(firstSubscriber);
			myPublisher.add(lastSubscriber);
			// execute 
			myPublisher.publish(MSG1);
			// verify mock behavior
			firstSubscriber.verify();
			lastSubscriber.verify();
			// show mock expectation error message if any
			assertNull(firstSubscriber.errorMessage());
		}  			
		public function canPublishEvenWithoutASubscriber():void{
			var myPublisher:Publisher = new Publisher();
			// execute 
			myPublisher.publish(MSG1);
		}  			
	}
}

// Inner Class
import org.mock4as.Mock;
import com.mocksamples.subscriber.Subscriber;

class MockSubscriber extends Mock implements Subscriber {
	public function receive(message:String):void
	{
		record("receive", message);
	}
}
    
